//
//  UserCenterViewController.swift
//  ZNZXSuperMarket
//
//  Created by 四川中农 on 2018/7/24.
//  Copyright © 2018年 四川中农. All rights reserved.
//

import UIKit

/// 我的  个人中心

class UserCenterViewController: BaseViewController {
    
    
    @IBOutlet weak var headerImg: UIImageView!
    @IBOutlet weak var userName: UILabel!
    @IBOutlet weak var centerBaseView: UIView!
    @IBOutlet weak var collectionView: UICollectionView!
    @IBOutlet weak var collectionViewHeight: NSLayoutConstraint!
    @IBOutlet weak var scrollView: UIScrollView!
    @IBOutlet weak var shadowView: UIView!
    @IBOutlet weak var balanceLabel: UILabel!//我的余额
    @IBOutlet weak var debtLabel: UILabel!//我的欠款
    @IBOutlet weak var couponCount: UILabel! // 优惠券数量
    
    @IBOutlet weak var firstView: UIView!
    @IBOutlet weak var thirdView: UIView!
    
    var balance = ""
    
    let titleArray = ["我的订单","报表统计","余额储值","发票信息","兼职服务","新品需求","客户服务","领手写单"]
    let imageArray = ["mine_icon_dingdan","mine_icon_tj","mine_icon_chuzhi","mine_icon_fpxx","mine_icon_jzfw","mine_icon_xpxq","mine_icon_kf","mine_icon_sxd"]
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        setStyle()
        
        let headerTap = UITapGestureRecognizer.init(target: self, action: #selector(headerTapClick))
        self.headerImg.isUserInteractionEnabled = true
        self.headerImg.addGestureRecognizer(headerTap)
    }
    
    @objc func headerTapClick(){
        let ctrl = Utils.instantiateInitialViewControllerWith(storyBoardName: "Main", identitier: "ShopDetailTableViewController") as! ShopDetailTableViewController
        ctrl.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(ctrl, animated: true)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(true, animated: true)
        
        if Utils.isLogined() {
            self.headerImg.my_setImage(url: Utils.getUserDefaulsFor(key: "storeImg") as! String, placeholder: Api.header.rawValue)
            self.userName.text = (Utils.getUserDefaulsFor(key: "storeName") as? String)
            self.getUserPerson()
        }
        
    }
    
    func getUserPerson(){
        HttpRequest.requestData(.post, URLString: Api.userPerson.rawValue, parameters: nil) { (result) in
            if result["msg"] as! String == "success"{
                let dic = result["data"] as! [String:Any]
                self.updateUserDetails(balance: dic["money"] as! Double, debt:dic["arrears"] as! Double, count: dic["couponSize"] as! Int)
            }else{
                if result["isLogin"] != nil {
                    PKhud.showText(text: result["data"] as! String)
                    Utils.goLoginCtrol(ctrl: self, isHidenBottomBar: true)
                }
                PKhud.showText(text: result["data"] as! String)
            }
        }
    }
    
    func updateUserDetails(balance:Double,debt:Double,count:Int){
        
        self.balance = "\(balance)"
        
        var money = "￥" + "\(balance)"
        var attrebute = NSMutableAttributedString.init(string: money)
        attrebute.addAttributes([NSAttributedStringKey.font:UIFont.systemFont(ofSize: 18)], range: NSString.init(string: money).range(of: "\(balance)"))
        self.balanceLabel.attributedText = attrebute
        
        money = "￥" + "\(debt)"
        attrebute = NSMutableAttributedString.init(string: money)
        attrebute.addAttributes([NSAttributedStringKey.font:UIFont.systemFont(ofSize: 18)], range: NSString.init(string: money).range(of: "\(debt)"))
        
        self.debtLabel.attributedText = attrebute
        self.couponCount.text = "\(count)"
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    // MARK:设置
    @IBAction func setButtonMethod(_ sender: UIButton) {
        let ctrl = Utils.instantiateInitialViewControllerWith(storyBoardName: "Main", identitier: "SetTableViewController") as! SetTableViewController
        ctrl.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(ctrl, animated: true)
    }
    
    // MARK:我的余额 Method
    @IBAction func BalanceButtonClick(_ sender: UIButton) {
        let ctrl = Utils.instantiateInitialViewControllerWith(storyBoardName: "Main", identitier: "MyBalanceTableViewController") as! MyBalanceTableViewController
        ctrl.hidesBottomBarWhenPushed = true
        ctrl.balance = self.balance
        self.navigationController?.pushViewController(ctrl, animated: true)
    }
    
    // MARK:欠款Method
    @IBAction func DebtButtonClick(_ sender: UIButton) {
        let ctrl = Utils.instantiateInitialViewControllerWith(storyBoardName: "Main", identitier: "DebtDetailTableViewController") as! DebtDetailTableViewController
        ctrl.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(ctrl, animated: true)
    }
    
    // MARK: 优惠券Method
    @IBAction func couponButtonClick(_ sender: UIButton) {
        let ctrl = Utils.instantiateInitialViewControllerWith(storyBoardName: "Main", identitier: "MyCouponTableViewController") as! MyCouponTableViewController
        ctrl.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(ctrl, animated: true)
    }
    
    

}


extension UserCenterViewController:UICollectionViewDelegate,UICollectionViewDataSource{
    
    func setStyle(){
        if #available(iOS 11, *) {
            self.scrollView.contentInsetAdjustmentBehavior = .never
        }else{
            self.automaticallyAdjustsScrollViewInsets = false
        }
        
        self.firstView.setCornerRadio(radio: 5, isMask: true)
        self.thirdView.setCornerRadio(radio: 5, isMask: true)
        
        let width = UIScreen.ScreenWidth/(375/130)
        self.shadowView.setCornerRadio(radio: width/2, isMask: false)
        self.shadowView.setShadow(color: "#000000,", offset: CGSize.init(width: 0, height: 2), radius: 10, opacity: 0.2)
        self.headerImg.setCornerRadio(radio: width/2, isMask: true)
        self.headerImg.setBorder(color: "#000000,", width: 2)
        
        self.centerBaseView.setCornerRadio(radio: 5, isMask: false)
        self.centerBaseView.setShadow(color: "000000", offset: CGSize.init(width: 0, height: 1.5), radius: 8, opacity: 0.1)

        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.itemSize = CGSize.init(width: UIScreen.ScreenWidth/4, height: 96)
        flowLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0)
        flowLayout.minimumLineSpacing = 0
        flowLayout.minimumInteritemSpacing = 0
        self.collectionView.setCollectionViewLayout(flowLayout, animated: true)
        self.collectionViewHeight.constant = 96 * 2 + 20
    }
    
    
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
         return 8
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCollectionViewCell", for: indexPath) as! MyCollectionViewCell
        cell.changeContent(imgName: self.imageArray[indexPath.row], title: self.titleArray[indexPath.row])
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        guard Utils.isLogined() else {
            Utils.goLoginCtrol(ctrl: self, isHidenBottomBar: true)
            return
        }
        switch indexPath.row {
        case 0:
            // order
            let ctrl = Utils.instantiateInitialViewControllerWith(storyBoardName: "Main", identitier: "OrderListViewController") as! OrderListViewController
            ctrl.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(ctrl, animated: true)
        case 1:
            //报表
            let ctrl = Utils.instantiateInitialViewControllerWith(storyBoardName: "Main", identitier: "EarningsStatementTableViewController") as! EarningsStatementTableViewController
            ctrl.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(ctrl, animated: true)
        case 2:
            //余额
            let ctrl = Utils.instantiateInitialViewControllerWith(storyBoardName: "Main", identitier: "BalanceRechargeTableViewController") as! BalanceRechargeTableViewController
            ctrl.myBalance = self.balance
            ctrl.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(ctrl, animated: true)
        case 3:
            // 发票信息
            let ctrl = Utils.instantiateInitialViewControllerWith(storyBoardName: "Main", identitier: "InvoiceMsgViewController") as! InvoiceMsgViewController
            ctrl.hidesBottomBarWhenPushed = true
            ctrl.title = "发票信息"
            self.navigationController?.pushViewController(ctrl, animated: true)
        case 5:
            // 新品需求
            let ctrl = Utils.instantiateInitialViewControllerWith(storyBoardName: "Main", identitier: "NewGoodsDemandViewController") as! NewGoodsDemandViewController
            ctrl.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(ctrl, animated: true)
        case 6:
            let ctrl = Utils.instantiateInitialViewControllerWith(storyBoardName: "Main", identitier: "InvoiceMsgViewController") as! InvoiceMsgViewController
            ctrl.hidesBottomBarWhenPushed = true
            ctrl.title = "客户服务"
            self.navigationController?.pushViewController(ctrl, animated: true)
//            let ctrl = Utils.instantiateInitialViewControllerWith(storyBoardName: "Main", identitier: "CustomerServiceViewController") as! CustomerServiceViewController
//            ctrl.hidesBottomBarWhenPushed = true
//            self.navigationController?.pushViewController(ctrl, animated: true)
        default:
            break
        }
    }
}




























